package com.vegetable.modules.service.wx.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.modules.entity.sys.SysUserEntity;
import com.vegetable.modules.entity.wx.WxDepartment;
import com.vegetable.modules.entity.wx.SysUserDepartment;
import com.vegetable.modules.mapper.sys.SysUserDao;
import com.vegetable.modules.mapper.wx.WxDepartmentDao;
import com.vegetable.modules.mapper.wx.SysUserDepartmentDao;
import com.vegetable.modules.service.wx.WxDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 企业微信部门服务实现类
 *
 * @author Qoder
 */
@Slf4j
@Service
public class WxDepartmentServiceImpl extends ServiceImpl<WxDepartmentDao, WxDepartment> implements WxDepartmentService {

    @Autowired
    private WxDepartmentDao wxDepartmentDao;

    @Autowired
    private SysUserDepartmentDao sysUserDepartmentDao;
    
    @Autowired
    private SysUserDao sysUserDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDepartment(WxDepartment department) {
        wxDepartmentDao.insert(department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDepartments(List<WxDepartment> departments) {
        for (WxDepartment department : departments) {
            // 先尝试更新，如果不存在则插入
            WxDepartment existing = wxDepartmentDao.selectById(department.getId());
            if (existing != null) {
                wxDepartmentDao.updateById(department);
            } else {
                wxDepartmentDao.insert(department);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserDepartment(SysUserDepartment userDepartment) {
        // 先删除已存在的记录
        QueryWrapper<SysUserDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userDepartment.getUserId())
                .eq("department_id", userDepartment.getDepartmentId());
        sysUserDepartmentDao.delete(queryWrapper);
        
        // 插入新记录
        sysUserDepartmentDao.insert(userDepartment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserDepartments(List<SysUserDepartment> userDepartments) {
        for (SysUserDepartment userDepartment : userDepartments) {
            saveUserDepartment(userDepartment);
        }
    }

    @Override
    public List<WxDepartment> getSysUserDepartments(Long sysUserId) {
        // 1. 根据系统用户ID获取用户所属部门ID列表
        QueryWrapper<SysUserDepartment> userDeptQueryWrapper = new QueryWrapper<>();
        userDeptQueryWrapper.eq("user_id", sysUserId);
        List<SysUserDepartment> userDepartments = sysUserDepartmentDao.selectList(userDeptQueryWrapper);
        
        // 2. 获取部门信息
        if (!userDepartments.isEmpty()) {
            QueryWrapper<WxDepartment> deptQueryWrapper = new QueryWrapper<>();
            deptQueryWrapper.in("id", userDepartments.stream()
                    .map(SysUserDepartment::getDepartmentId)
                    .toArray());
            return wxDepartmentDao.selectList(deptQueryWrapper);
        }
        
        return Collections.emptyList();
    }

    /**
     * 修改用户所属部门
     * 建立系统用户与部门的关联关系
     * @param sysUserId 系统用户ID
     * @param departmentIds 部门ID列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserDepartments(Long sysUserId, List<Long> departmentIds) {
        log.info("开始更新用户部门信息: sysUserId={}, departmentIds={}", 
                sysUserId, departmentIds);
        
        // 1. 根据系统用户ID获取系统用户信息
        SysUserEntity sysUser = sysUserDao.selectById(sysUserId);
        if (sysUser == null) {
            log.warn("系统用户不存在: sysUserId={}", sysUserId);
            throw new RuntimeException("系统用户不存在");
        }
        
        // 2. 删除用户现有的所有部门关联
        QueryWrapper<SysUserDepartment> deleteUserDeptQueryWrapper = new QueryWrapper<>();
        // 确保只删除当前用户的部门关联
        deleteUserDeptQueryWrapper.eq("user_id", sysUserId);
        log.info("准备删除用户部门关联，查询条件: user_id={}", sysUserId);
        int deletedCount = sysUserDepartmentDao.delete(deleteUserDeptQueryWrapper);
        log.info("删除用户原有部门关联记录数量: deletedCount={}", deletedCount);
        
        // 3. 重新建立用户与部门的关联
        if (departmentIds != null && !departmentIds.isEmpty()) {
            log.info("开始为用户 {} 添加新的部门关联，部门数量: {}", sysUserId, departmentIds.size());
            List<SysUserDepartment> newUserDepartments = new ArrayList<>();
            
            for (Long departmentId : departmentIds) {
                // 准备用户部门关联信息
                SysUserDepartment userDepartment = new SysUserDepartment();
                userDepartment.setUserId(sysUserId);
                userDepartment.setDepartmentId(departmentId);
                
                newUserDepartments.add(userDepartment);
                log.info("准备插入用户部门关联记录: userId={}, departmentId={}", 
                        sysUserId, departmentId);
            }
            
            // 批量插入用户部门关联记录
            if (!newUserDepartments.isEmpty()) {
                for (SysUserDepartment userDepartment : newUserDepartments) {
                    // 使用saveUserDepartment方法确保正确处理重复记录
                    saveUserDepartment(userDepartment);
                }
                log.info("批量插入 {} 条用户部门关联记录", newUserDepartments.size());
            }
        } else {
            log.info("部门ID列表为空或null，不插入任何部门关联记录");
            if (departmentIds != null && departmentIds.isEmpty()) {
                log.info("用户 {} 的部门列表为空数组，已清除该用户的所有部门关联", sysUserId);
            }
        }
        
        log.info("用户部门信息更新完成: sysUserId={}", sysUserId);
    }
}